# -*- coding: gbk -*-
# @File  : rabbitmq_producer.py
# @Time  : 2022-05-09  00:13
# @Author: Charlotte
import pickle
import time
import jsonpath
import pika
import requests
from requests_html import HTMLSession
session = HTMLSession()
from loguru import logger


class LOLProducerSpider(object):
    def __init__(self):
        self.start_url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?ts=2749542'
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36',
        }
        self.connection_rabbitmq = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
        self.channel = self.connection_rabbitmq.channel()
        self.channel.queue_declare(queue='lol',durable=True)


    def send_url(self):
        response = session.get(self.start_url, headers=self.headers)
        json_data = response.json()
        num_hero = 10
        hero_id = jsonpath.jsonpath(json_data, '$..heroId')[:num_hero]
        for heroid in hero_id:
            send_url = 'https://game.gtimg.cn/images/lol/act/img/js/hero/{}.js?ts=2749545'.format(heroid)
            response = requests.Request('GET',url=send_url)
            self.channel.basic_publish(
                exchange='',
                routing_key='lol',
                properties=pika.BasicProperties(
                    delivery_mode=2,
                ),
                body=pickle.dumps(response),
            )
            print('push into consumer {}'.format(send_url))


    def main(self):
        self.send_url()




if __name__ == '__main__':

    l = LOLProducerSpider()
    l.main()
